package xyz.matrix.web;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.mysql.cj.util.StringUtils;

import xyz.matrix.dao.UserDao;
import xyz.matrix.model.User;
import xyz.matrix.util.DbUtil;

public class LoginServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doPost(request, response);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String userName = request.getParameter("userName");
		String password = request.getParameter("password");
		if (StringUtils.isEmptyOrWhitespaceOnly(userName) || StringUtils.isEmptyOrWhitespaceOnly(password)) {
			request.setAttribute("error", "用户名或密码不能为空！");
			request.getRequestDispatcher("index.jsp").forward(request, response);
		}
		User user = new User(userName,password);
		UserDao userDao = new UserDao();
		DbUtil dbUtil = new DbUtil();
		Connection con = null;
		User currentUser = null;
		try {
			currentUser = new User();
			con = dbUtil.getCon();
			currentUser = userDao.login(con, user);
			if (currentUser != null) {
				System.out.println("用户：" + currentUser.getUserName() + " 上线了！");
				HttpSession session = request.getSession();
				session.setAttribute("currentUser", currentUser);
				response.sendRedirect("main.jsp");
			} else {
				System.out.println("用户名或者密码错误！");
				request.setAttribute("error", "用户名或者密码错误！");
				request.setAttribute("userName", userName);
				request.setAttribute("password", password);
				request.getRequestDispatcher("index.jsp").forward(request, response);
			}
			
			
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				con.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	
}
